var localVideo = document.querySelector('#localVideo');
var remoteVideo = document.querySelector('#remoteVideo');
var btnStart = document.querySelector('#start');
var btnCall = document.querySelector('#call');
var btnHangup = document.querySelector('#hangup');
var localSdp = document.querySelector('#localSdp');
var remoteSdp = document.querySelector('#remoteSdp');
var localStream;

var pc1;
var pc2;
function gotMediaStream(stream){ 
    localVideo.srcObject = stream;
    localStream = stream;
}


function start(){
    
    if(!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices){
        alert("Media devices not supported");
    }else{
        navigator.mediaDevices.getDisplayMedia({
            video: true,
            audio: true,
        }).then(gotMediaStream) 
        .catch(err => {
            console.log("navigator.mediaDevices.getDisplayMedia fail");
            
        });
    }

}

function call(){
    pc1 = new RTCPeerConnection();
    pc2 = new RTCPeerConnection();
    pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
    pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
    
    pc2.ontrack = function(e){
        remoteVideo.srcObject = e.streams[0];
    }
    localStream.getTracks().forEach(track => pc1.addTrack(track, localStream));
    
    var offerOptions = {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1
    }
    pc1.createOffer(offerOptions)
    .then(desc => {
        localSdp.value = desc.sdp;
        pc1.setLocalDescription(desc);
        pc2.setRemoteDescription(desc);
        pc2.createAnswer()
        .then(desc2 => {
            pc2.setLocalDescription(desc2);
            pc1.setRemoteDescription(desc2);
            remoteSdp.value = desc2.sdp;
        })
        .catch(err => console.log("pc2.createOffer catch"));
    })
    .catch(err => console.log("pc1.createOffer fail"));
}


function hangup(){
    pc1.close();
    pc2.close();
    pc1 = null;
    pc2 = null;
}




btnStart.onclick = start;
btnCall.onclick = call;
btnHangup.onclick = hangup;

